<template>
  <div v-loading="loading" class="px-5 py-4 bg-white">
    <el-row :gutter="0">
      <el-col :span="24" :xs="24">
        <!-- 标题 -->
        <HeadTitle text="设备管理"/>
      </el-col>
      <!-- 搜索 -->
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="80px"
        label-position="left"
      >
        <el-col :span="24" :xs="24">
          <el-form-item label="设备编号" prop="equipmentNo">
            <el-input
              v-model="queryParams.equipmentNo"
              placeholder="请输入设备编号"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item v-if="null == isDept" label="科室" prop="deptId">
            <el-select @change="getList"
              v-model="queryParams.deptId"
              placeholder="全部"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="item in deptOption"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="null == isDept" label="是否分配" prop="allocationFlag">
            <el-select @change="getList"
              v-model="queryParams.allocationFlag"
              placeholder="全部"
              clearable
              style="width: 240px"
            >
              <el-option label="已分配" value="1"/>
              <el-option label="未分配" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item v-if="null == isDept" label="入院时间" prop="dateRange">
            <el-date-picker @change="getList"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getList">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <!-- 按钮 -->
    <el-row v-if="null == isDept" justify="space-between">
      <el-col :span="4">
        <el-button type="primary" @click="open = true" :disabled="disabled">
          <svg aria-hidden="true" class="w-4 h-4 mr-2" style="fill: #fff">
            <use :xlink:href="`#icon-alloc`"/>
          </svg>
          批量分配
        </el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-row :gutter="0" class="mt-4">
      <el-col :span="24">
        <Table
          :column="tableColumn"
          :table-data="EqList"
          :option="option"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          @selection-change="handleSelectionChange"
        >
          <template #status="scope">
            <div class="flex justify-center">
              <svg aria-hidden="true" class="w-4 h-4 mr-2">
                <use
                  :xlink:href="`#icon-${
                    scope.row.allocationFlag == '1' ? 'checkedIn' : 'notCheckedIn'
                  }`"
                />
              </svg>
              <span class="text-xs">{{
                  scope.row.allocationFlag == '1' ? '已分配' : '未分配'
                }}</span>
            </div>
          </template>
          <template #state="scope">
            <el-tag v-if="scope.row.useFlag==='1'" class="ml-2" type="success">使用中</el-tag>
            <el-tag v-if="scope.row.useFlag==='0'" class="ml-2" type="info">未使用</el-tag>
          </template>
          <template #failure="scope">
            <el-tag v-if="scope.row.failureFlag == '0'" size="mini" type="success">正常</el-tag>
            <el-tag v-if="scope.row.failureFlag == '1'" size="mini" type="danger">故障</el-tag>
          </template>
          <template #battery="scope">
            <div v-if="scope.row.batteryPercentage != null && scope.row.batteryPercentage != undefined">
              <p v-if="scope.row.batteryPercentage >= 81" style="color: #63b62f">
                {{ scope.row.batteryPercentage + '%' }}</p>
              <p v-if="scope.row.batteryPercentage <= 80 && scope.row.batteryPercentage >= 61" style="color: #c5c318">
                {{ scope.row.batteryPercentage + '%' }}</p>
              <p v-if="scope.row.batteryPercentage <= 60 && scope.row.batteryPercentage >= 41" style="color: #f3971c">
                {{ scope.row.batteryPercentage + '%' }}</p>
              <p v-if="scope.row.batteryPercentage <= 40 && scope.row.batteryPercentage >= 21" style="color: #e8540c">
                {{ scope.row.batteryPercentage + '%' }}</p>
              <p v-if="scope.row.batteryPercentage <= 20" style="color: #df1214">
                {{ scope.row.batteryPercentage + '%' }}</p>
              <div style="font-size: 12px; color: #999;">{{ "(更新时间：" + scope.row.acquisitionTime + ")" }}</div>
            </div>
            <div v-else>
              -
            </div>
          </template>
          <template #alloc="scope">
            <svg
              aria-hidden="true"
              class="w-4 h-4 mr-2"
              style="fill: #00a991"
              @click="(open = true), handleSelectionChange(scope.row, 1)"
            >
              <use xlink:href="#icon-alloc"/>
            </svg>
          </template>
          <template #compliance="scope">
            {{ scope.row.complianceCount + "次" }}
          </template>
        </Table>
      </el-col>
    </el-row>

    <el-dialog title="分配科室" v-model="open" width="400px" append-to-body>
      <el-form
        :model="form"
        ref="eqRef"
        label-position="left"
        label-width="80px"
        size="default"
      >
        <el-form-item label="科室选择" prop="deptId">
          <el-select v-model="form.deptId" style="width: 240px" clearable>
            <el-option
              v-for="(item, index) in deptOption"
              :key="index"
              :label="item.label"
              :value="item.id"
            />
            <el-option label="不分配" value=""/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(eqRef)">确 定</el-button>
          <el-button @click=";(form.deptId = undefined), (open = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {adEq, listEq} from '@/api/eq'
import {getDeptTree} from '@/api/user'
import {ElMessageBox, FormInstance} from 'element-plus'
import {reactive, ref, toRefs} from 'vue'
import {useCache} from '@/hooks/web/useCache'
import {useAppStore} from '@/store/modules/app'

const showSearch = ref(true)

const {wsCache} = useCache()
const appStore = useAppStore()

const open = ref(false)
const queryRef = ref()
const eqRef: any = ref(null)
const dateRange = ref([]) //时间
const deptOption: any = ref([]) //科室选择
const disabled = ref(true)
const isDept = ref(wsCache.get(appStore.getUserInfo).deptId)
const loading = ref(false)

interface FormType {
  deptId: NumUn //科室ID
  equipmentList: Array<{
    id: number
    equipmentType: string
    equipmentNo: string
  }> //设备列表
}

interface QueryType {
  pageSize: number
  pageNum: number
  equipmentType?: string //设备类型
  equipmentNo?: number //设备编号
  deptId?: number //科室ID
  allocationFlag?: string //是否分配 0=未分配；1=已分配
  startTime?: string //开始时间
  endTime?: string //结束时间
  overdue?: number
}

interface DataType {
  form: FormType
  queryParams: QueryType
}

const data = reactive<DataType>({
  form: {
    deptId: undefined, //科室id
    equipmentList: [] //设备列表
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
})

const {queryParams, form} = toRefs(data)

//表格配置
const tableColumn = [
  {type: 'selection'},
  {prop: 'equipmentNo', label: '设备编号', align: 'center', minWidth: 200, showOverflowTooltip: true},
  {prop: 'allocationFlag', label: '是否分配', align: 'center', slot: 'status', width: 100},
  {prop: 'deptName', label: '科室', align: 'center', showOverflowTooltip: true},
  {prop: 'useTimes', label: '使用次数', align: 'center'},
  {prop: 'batteryPercentage', label: '剩余电量', align: 'center', slot: 'battery', width: 280},
  {prop: 'useFlag', label: '使用状态', align: 'center', slot: 'state'},
  {prop: 'failureFlag', label: '运行状态', align: 'center', slot: 'failure'}

]
const isShowOpt = () => {
  if (null == isDept.value) {
    tableColumn.push({
      label: '操作',
      align: 'center',
      buttons: [
        {name: '分配', slot: 'alloc'},
      ]
    })
  }
}
isShowOpt()
tableColumn as Table.Column[]

interface State {
  EqList: Array<object>
  option: Table.Option
}

const state = reactive<State>({
  EqList: [],
  option: {
    loading: false,
    showPagination: true,
    height: 580,
    paginationConfig: {
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  }
})
const {EqList, option} = toRefs(state)

//获取床位列表
const getList = () => {
  if (dateRange.value?.length) {
    queryParams.value.startTime = dateRange.value[0] //开始时间
    queryParams.value.endTime = dateRange.value[1] //结束时间
  }
  queryParams.value.equipmentType = "TJ02";
  loading.value = true;
  listEq(queryParams.value).then((res: any) => {
    loading.value = false;
    EqList.value = res.rows
    if (option.value.paginationConfig) {
      option.value.paginationConfig.total = res.total
    }
    option.value.loading = false
  })
}

/** 科室 */
const DeptTree = () => {
  getDeptTree().then((res: any) => {
    deptOption.value = res.data
  })
}

/** 重置按钮操作 */
const resetQuery = (queryRef: { resetFields: () => void }) => {
  queryRef.resetFields()
  dateRange.value = []
  queryParams.value.startTime = '' //开始时间
  queryParams.value.endTime = '' //结束时间
  getList()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any, type?: number) => {
  form.value.equipmentList = []
  if (type == 1) {
    form.value.equipmentList = [
      {
        id: selection.id,
        equipmentType: selection.equipmentType,
        equipmentNo: selection.equipmentNo
      }
    ]
  } else {
    //批量分配
    selection.forEach((val) => {
      let data = {
        id: val.id,
        equipmentType: val.equipmentType,
        equipmentNo: val.equipmentNo
      }
      form.value.equipmentList.push(data)
    })
  }

  if (form.value.equipmentList.length) {
    disabled.value = false
  } else {
    disabled.value = true
  }
}

/** 提交按钮 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      adEq(form.value).then((res: any) => {
        open.value = false
        ElMessageBox.alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          res.msg +
          '</div>',
          '分配结果',
          {dangerouslyUseHTMLString: true}
        )
        getList()
      })
      form.value.deptId = undefined
    } else {
      console.log('error submit!', fields)
    }
  })
}

/** 分页*/
const handleCurrentChange = (pageNum: number) => {
  if (option.value.paginationConfig) {
    option.value.paginationConfig.currentPage = pageNum
    queryParams.value.pageNum = pageNum
  }
  getList()
}

/** 分页*/
const handleSizeChange = (pageSize: number) => {
  if (option.value.paginationConfig) {
    option.value.paginationConfig.pageSize = pageSize
    queryParams.value.pageSize = pageSize
  }
  getList()
}

getList()
if (null == isDept.value) {
  DeptTree()
}
</script>
<style lang="less">
.el-button--primary {
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
}
</style>
